import logging
from datetime import datetime
from common.permission.models import Permission, MenuNode, PageBlockField
from common.utils.db import list_object, get_object

_LOGGER = logging.getLogger(__name__)


def get_perm(query_dct):
    return get_object(query_dct, Permission)


def list_perm(query_dct):
    return list_object(query_dct, Permission)


def create_perm(url, request_method, min_role_level):
    perm = Permission(
        url=url,
        request_method=request_method,
        min_role_level=min_role_level,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )
    perm.save()
    return perm


def update_perm(permission_id, min_role_level, allowed_page_id, desc):
    perm = Permission.objects.filter(id=permission_id).select_for_update().first()
    if perm:
        perm.min_role_level = min_role_level
        perm.desc = desc
        perm.allowed_page_id = allowed_page_id
        perm.save()


def get_merchant_permission_options(merchant_id):
    merchant_pages = MenuNode.objects.filter(merchant_id=merchant_id, is_page=True).order_by(
        'parent_section_id').all()
    merchant_page_list = []
    for page in merchant_pages:
        merchant_page_list.append({"key": page.section_id, "value": page.section_name})
    return merchant_page_list


def get_base_event_list(merchant_id, merchant_permission, is_root=False):
    base_event_page_nodes = MenuNode.objects.filter(tree_path__contains=',1000,', is_page=True,
                                                    merchant_id=merchant_id).all()
    base_event_list = []
    for event_id in [node.section_id for node in base_event_page_nodes]:
        if ',' + event_id + ',' not in merchant_permission and not is_root:
            continue
        base_event_list.append(event_id)
    return base_event_list


def get_biz_menu_list(merchant_id, merchant_permission, is_root=False):
    biz_menu_list = []
    merchant_pages = MenuNode.objects.filter(merchant_id=merchant_id, is_page=True).exclude(
        tree_path__contains=',1000,').all()
    for page_item in merchant_pages:
        if ',' + page_item.section_id + ',' not in merchant_permission and not is_root:
            continue
        biz_menu_list.append(str(page_item.parent_section_id))
        biz_menu_list.append(page_item.section_id)
    return list(set(biz_menu_list))


def create_page_block_field(role_id, logical_page_id, field_list):
    page_node = MenuNode.objects.filter(section_id=logical_page_id).first()
    page_id = page_node.id
    PageBlockField.objects.filter(role_id=role_id, menu_node_id=page_id).delete()
    for field in field_list:
        PageBlockField.objects.get_or_create(
            role_id=role_id, menu_node_id=page_id, exclude_field_name=field,
            defaults={
                'role_id': role_id,
                'menu_node_id': page_id,
                'exclude_field_name': field
            })


def get_role_page_block_field(merchant_id, role_id, logical_page_id):
    page_node = MenuNode.objects.filter(section_id=logical_page_id, merchant_id=merchant_id).first()
    page_id = page_node.id if page_node else None
    block_fields = PageBlockField.objects.filter(role_id=role_id, menu_node_id=page_id).all()
    return [block_field.exclude_field_name for block_field in block_fields]
